import axios from "axios";
import qs from "qs";
// import { WEB_URL } from "@/config";
// import { ElMessage } from "element-plus";
// import { getUserInfo, removeUserInfo } from "@/service";
// import { getCookie } from "./cookies";
import { useLoading } from '../store/loading';
import { getToken, removeToken } from "@/utils/auth"; // 验权
import { useRouter } from "vue-router";
const router = useRouter();



const pendingRequest = new Map();

function generateReqKey (config) {
  const { method, url, params, data } = config;
  return [method, url, qs.stringify(params), qs.stringify(data)].join("&");
}

function addPendingRequest (config) {
  const requestKey = generateReqKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel);
      }
    });
}

function removePendingRequest (config) {
  const requestKey = generateReqKey(config);
  if (pendingRequest.has(requestKey)) {
    const cancelToken = pendingRequest.get(requestKey);
    cancelToken(requestKey);
    pendingRequest.delete(requestKey);
  }
}

const baseRequest = axios.create({
  headers: {
    "Content-Type": "application/json",
  },
  timeout: 5000,
});

const loading = useLoading();
// 进行请求拦截
baseRequest.interceptors.request.use(
  (config) => {
    // let userTaken = getCookie("SESSIONID");
    // if (userTaken) {
    //   config.headers["token"] = userTaken;
    // }
    let token = getToken();
    if (token) {
      // 项目中token的key值 根据后端接口要求进行修改
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    loading.visible = true;
    removePendingRequest(config); // 检查是否存在重复请求，若存在则取消已发的请求
    addPendingRequest(config); // 把当前请求信息添加到pendingRequest对象中
    return config;
  },
  (error) => {
    console.log('11111111111111', error);
    loading.visible = false;
    return Promise.reject(error);
  }
);
// 响应拦截
baseRequest.interceptors.response.use(
  (response) => {
    removePendingRequest(response.config); // 从pendingRequest对象中移除请求
    const res = response.data;
    console.log(res, 'res');
    console.log(response, 'response');
    if (response.headers.filename) {
      return response;
    }


    // 这个根据具体内容判断 后端接口情况 处理或不处理
    if (res.code == 200) {
      // ElMessage({
      //   message: res.msg,
      //   type: "error",
      //   duration: 3 * 1000,
      // });
      loading.visible = false;
      return res;
    } else {
      return res;
    }
  },
  (error) => {
    removePendingRequest(error.config || {}); // 从pendingRequest对象中移除请求

    if (axios.isCancel(error)) {
      console.log("已取消的重复请求：" + error.message);
    } else {
      // 处理异常情况，根据项目实际情况处理
      if (error && error.response) {
        console.log('error.response', error.response, error.response.data.code);
        // 根据约定的响应码处理
        switch (error.response.data.code) {
          case -1:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            });
            break;
          case 400:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            });
            break;
          case 401:
            // 登錄過期，重新登錄，或者跳轉到登錄頁面
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            });
            window.location.href = "/login";
            removeToken(); // 清除token
            break;
          case 402:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            })
            break;
          // return error.response;
          // break;
          case 403:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            })
            break;
          case 404:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            })
            break;
          case 500:
            ElNotification({
              message: error.response.data.msg,
              type: "error",
            })
            break;
          case 502:
            error.message = "服务器端出错";
            break;
          // default:
          //   error.message = '暂未登录，请登录之后';
        }
      } else {
        // 超时处理
        ElNotification({
          message: '服务器响应超时，请刷新当前页',
          type: "error",
        })
      }
      // ElMessage({
      //   message: error.message,
      //   type: "error",
      //   duration: 3 * 1000,
      // });
    }
    loading.visible = false;
    return Promise.reject(error.response);
  }
);

export default baseRequest;
